package cur.nature.admin.service;

import cur.nature.admin.dao.Admin_MidDao;
import cur.nature.admin.dao.Admin_UserDao;
import cur.nature.admin.model.po.Admin_Mid_UserDeptPO;
import cur.nature.admin.model.po.Admin_Mid_UserRolePO;
import cur.nature.admin.model.po.Admin_UserPO;
import cur.nature.admin.model.vo.Admin_UserVO;
import cur.nature.framework.core.exception.BizException;
import cur.nature.framework.core.mirco.MircoIdUtil;
import cur.nature.framework.core.util.IdUtil;
import cur.nature.framework.core.util.JWTUtil;
import cur.nature.framework.core.util.SnowflakeIdUtil;
import cur.nature.framework.core.util.StringUtil;
import cur.nature.framework.mvc.auth.LoginUser;
import cur.nature.framework.mvc.crud.CrudService;
import cur.nature.tinyorm.core.bean.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户信息 Service
 * 作者：Auto Generator By wujian
 * 生成日期：2023-07-10 21:42:14
 */
@Service
public class Admin_UserService extends CrudService<Admin_UserPO, Admin_UserVO, Admin_UserDao> {
    public Admin_UserService(Admin_UserDao baseDao) {
        super(baseDao, Admin_UserPO.class, Admin_UserVO.class);
    }

    @Autowired
    private Admin_MidDao midDao;

    public PageBean<Admin_UserVO> list(Admin_UserVO.list_Param param) throws Exception {
        PageBean<Admin_UserVO> pageBean = getDao().list(param);
        // 设置部门与角色
        if (pageBean != null && pageBean.getList().size() > 0) {
            List<Admin_UserVO> list = pageBean.getList();
            // 查出角色
            List<Long> userIdList = list.stream().map(Admin_UserVO::getId).collect(Collectors.toList());
            List<Admin_Mid_UserRolePO> roleList = midDao.queryUserRole(userIdList);
            // 设置角色id
            if (roleList != null) {
                for (Admin_UserVO base : list) {
                    List<Long> roleIdList = roleList.stream().filter(s -> base.getId().compareTo(s.getUserId())==0)
                            .map(Admin_Mid_UserRolePO::getRoleId).toList();
                    base.setRoleId(roleIdList);
                }
            }
            // 查出部门
            List<Admin_Mid_UserDeptPO> deptList = midDao.queryUserDept(userIdList);
            // 设置部门id
            if (deptList != null) {
                for (Admin_UserVO base : list) {
                    List<Long> deptIdList = deptList.stream().filter(s -> base.getId().compareTo(s.getUserId())==0)
                            .map(Admin_Mid_UserDeptPO::getDeptId).toList();
                    base.setDeptId(deptIdList);
                }
            }
        }

        return pageBean;
    }

    @Transactional
    public int operate(List<Admin_UserVO> param) throws Exception {
        if (param == null || param.size() == 0) {
            return 0;
        }
        int rows = this.saveList(param);
        // 更新中间表
        for (Admin_UserVO base : param) {
            // 先清除相关数据
            if (base.getId() != null) {
                midDao.deleteUserRoleByUserId(base.getId());
                midDao.deleteUserDeptByUserId(base.getId());
            }
            // 插入中间表数据
            if (base.getOperateType() != 3) {
                // 角色
                List<Admin_Mid_UserRolePO> roleList = new ArrayList<>();
                for (Long roleId : base.getRoleId()) {
                    Admin_Mid_UserRolePO po = new Admin_Mid_UserRolePO();
                    po.setCreateBase();
                    po.setId(MircoIdUtil.generateId());
                    po.setRoleId(roleId);
                    po.setUserId(base.getId());
                    roleList.add(po);
                }
                getTemplate().getTemplateProxy().batchInsert(roleList);
                // 部门
                List<Admin_Mid_UserDeptPO> deptList = new ArrayList<>();
                for (Long dept : base.getDeptId()) {
                    Admin_Mid_UserDeptPO po = new Admin_Mid_UserDeptPO();
                    po.setCreateBase();
                    po.setId(MircoIdUtil.generateId());
                    po.setDeptId(dept);
                    po.setUserId(base.getId());
                    deptList.add(po);
                }
                getTemplate().getTemplateProxy().batchInsert(deptList);
            }
        }

        return rows;
    }

    /**
     * 登录
     *
     * @param param
     * @return
     */
    public Admin_UserVO loginBySession(Admin_UserVO.login.Param param) throws Exception {
        // 查出用户
        Admin_UserVO userVo = null;
        List<Admin_UserVO> userList = getDao().queryByCond(param);
        if (userList == null || userList.size() == 0) {
            throw new BizException("没有查到此用户,请检查");
        }
        // 查出用户
        List<Admin_UserVO> filterUserList = userList.stream().filter(s ->
                StringUtil.equals(s.getLoginPwd(), param.getPassword())).collect(Collectors.toList());
        // 校验
        if (filterUserList == null || filterUserList.size() == 0) {
            throw new BizException("用户密码不正确,请检查");
        }
        if (filterUserList.size() > 1) {
            throw new BizException("查出多个帐户,请检查");
        }
        userVo = filterUserList.get(0);
        return userVo;
    }

    public Admin_UserVO loginByJwt(Admin_UserVO.login.Param param) throws Exception {
        if (StringUtil.isEmpty(param.getToken())) {
            throw new BizException("token 为空, 请检查");
        }
        // 校验
        JWTUtil.Result tokenResult = JWTUtil.decodeToken(param.getToken());
        if (tokenResult == null) {
            throw new BizException("解析token异常, 请检查");
        }
        if (tokenResult.getStatus() == JWTUtil.Result.ERROR) {
            throw new BizException("解析token失败, 请检查");
        }
        if (tokenResult.getStatus() == JWTUtil.Result.EXPIRE) {
            throw new BizException("token已过期, 请检查");
        }
        if (tokenResult.getStatus() == JWTUtil.Result.OK) {
            final Long userId = Long.valueOf(tokenResult.getData());
            Admin_UserVO userVO = getDao().queryById(userId);
            if (userVO == null) {
                throw new BizException("查询用户信息异常, 请检查");
            }
            return userVO;
        }
        throw new BizException("token失败,并已结束, 请检查");
    }

    public LoginUser setResource(LoginUser.User user, LoginUser result) throws Exception {
        // 设置用户
        user.setPhoto("https://img2.baidu.com/it/u=1978192862,2048448374&fm=253&fmt=auto&app=138&f=JPEG?w=504&h=500");
        // @TODO 设置默认角色,以适应前端， 后期可删除
        user.setRoles(Arrays.asList("admin", "common"));
        // 查出有权限的菜单及资源
        List<LoginUser.Resource> resList = getDao().queryResById(user.getId());
        result.setResourceList(resList);
        return result;
    }

    public List<Admin_UserVO.listByKeyword_Res> listByKeyword(Admin_UserVO.listByKeyword_Param param) throws Exception {
        if (StringUtil.isEmpty(param.getKeyword()) && (param.getUserIdList() == null || param.getUserIdList().size() == 0)) {
            return new ArrayList<>();
        }
        List<Admin_UserVO.listByKeyword_Res> list = this.getDao().listByKeyword(param);
        return list;
    }

    public Admin_UserVO getByOpenId(final String openId) throws Exception {
        return this.getDao().queryByOpenId(openId);
    }
}

